package bin_tree.leetcode;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

// 中序遍历
public class Num94 {
    // 基于栈的迭代
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new LinkedList<>();
        if (root == null)
            return ret;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || (!stack.isEmpty())) {
            // 一路向左走一直走到最左侧的最后一个节点
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            // 当前左树已经全部入栈
            cur = stack.pop();
            // 此时访问根节点
            ret.add(cur.val);
            // 继续访问右子树
            cur = cur.right;
        }
        return ret;
    }
}
